from types import FunctionType, MethodType
from mtk.middleware.server import ServerSetup


def is_call_obj(obj):
    return isinstance(obj, (FunctionType, MethodType))


# @app.listener('before_server_start')
async def start_before(app, loop):
    await ServerSetup.init_all(app, loop)


# @app.listener('after_server_start')
async def notify_server_start(app, loop):
    print('Server successfully started!')


# @app.listener('before_server_stop')
async def notify_server_stopping(app, loop):
    print('Server shutting down!')


# @app.listener('after_server_stop')
async def after_stop(app, loop):
    await ServerSetup.close_all(app, loop)


def register_listener(app, before_server_start=True, after_server_start=True, before_server_stop=True, after_server_stop=True):
    if before_server_start:
        app.register_listener(start_before if not is_call_obj(before_server_start) else before_server_start, 'before_server_start')
    if after_server_start:
        app.register_listener(notify_server_start if not is_call_obj(after_server_start) else after_server_start, 'after_server_start')

    if before_server_stop:
        app.register_listener(notify_server_stopping if not is_call_obj(before_server_stop) else before_server_stop, 'before_server_stop')
    if after_server_stop:
        app.register_listener(after_stop if not is_call_obj(after_server_stop) else after_server_stop, 'after_server_stop')


